package com.bckj.fastboot.core.extra.license;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Windows 系统硬件信息获取实现类
 * 通过执行WMIC命令获取详细的硬件信息
 */
public class WindowsServerInfos extends AbstractServerInfos {

    @Override
    protected List<String> getIpAddress() throws Exception {
        // 使用 ipconfig 命令获取IP地址
        List<String> result = new ArrayList<>();
        List<String> ipconfigResult = execCmd("ipconfig");
        for (String line : ipconfigResult) {
            // 简化处理，实际应用中需要更精确的匹配逻辑
            if (line.trim().startsWith("IPv4 地址") || line.trim().startsWith("IPv4 Address")) {
                String[] parts = line.split(":");
                if (parts.length > 1) {
                    result.add(parts[1].trim());
                }
            }
        }
        return result;
    }

    @Override
    protected List<String> getMacAddress() throws Exception {
        List<String> result = new ArrayList<>();
        // 执行WMIC命令获取网络适配器MAC地址和名称 [6](@ref)
        List<String> macInfo = execCmd("wmic nic get MACAddress,Name");
        for (String line : macInfo) {
            line = line.trim();
            // 筛选出有效的MAC地址行（包含连字符且不是标题行）
            if (line.matches(".*([0-9A-Fa-f]{2}-){5}[0-9A-Fa-f]{2}.*")) {
                String[] parts = line.split("\\s+");
                if (parts.length > 0) {
                    // 排除虚拟机和虚拟网卡的MAC地址（按需调整）
                    if (!line.toLowerCase().contains("virtual") && 
                        !line.toLowerCase().contains("vmware") && 
                        !line.toLowerCase().contains("host-only")) {
                        result.add(parts[0]);
                    }
                }
            }
        }
        return result;
    }

    @Override
    protected String getCpuSerial() throws Exception {
        // 获取CPU序列号 [6,8](@ref)
        List<String> cpuInfo = execCmd("wmic cpu get ProcessorId");
        for (String line : cpuInfo) {
            line = line.trim();
            // 跳过标题行和空行
            if (!line.startsWith("ProcessorId") && !line.isEmpty() && 
                !line.contains("Copyright")) {
                return line;
            }
        }
        return "Unknown";
    }

    @Override
    protected String getMainBoardSerial() throws Exception {
        // 获取主板序列号 [7,8](@ref)
        List<String> boardInfo = execCmd("wmic baseboard get SerialNumber");
        for (String line : boardInfo) {
            line = line.trim();
            // 跳过标题行和空行
            if (!line.startsWith("SerialNumber") && !line.isEmpty() && 
                !line.contains("Copyright")) {
                return line;
            }
        }
        return "Unknown";
    }

    /**
     * 获取硬盘序列号（第一个物理硬盘）
     */
    public String getDiskSerial() throws Exception {
        // 获取硬盘序列号 [7,8](@ref)
        List<String> diskInfo = execCmd("wmic diskdrive where Index=0 get SerialNumber");
        for (String line : diskInfo) {
            line = line.trim();
            if (!line.startsWith("SerialNumber") && !line.isEmpty() && 
                !line.contains("Copyright")) {
                return line;
            }
        }
        return "Unknown";
    }

    /**
     * 获取系统UUID
     */
    public String getSystemUUID() throws Exception {
        // 获取系统UUID [6](@ref)
        List<String> uuidInfo = execCmd("wmic csproduct get UUID");
        for (String line : uuidInfo) {
            line = line.trim();
            if (!line.startsWith("UUID") && !line.isEmpty() && 
                !line.contains("Copyright")) {
                return line;
            }
        }
        return "Unknown";
    }

    /**
     * 执行系统命令并返回结果列表
     */
    private List<String> execCmd(String cmd) throws Exception {
        List<String> result = new ArrayList<>();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", cmd});
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK"))) { // 使用GBK编码避免中文乱码
                
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.trim().isEmpty()) {
                        result.add(line);
                    }
                }
            }
            process.waitFor();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            WindowsServerInfos info = new WindowsServerInfos();
            System.out.println("CPU序列号: " + info.getCpuSerial());
            System.out.println("主板序列号: " + info.getMainBoardSerial());
            System.out.println("磁盘序列号: " + info.getDiskSerial());
            System.out.println("系统UUID: " + info.getSystemUUID());
            
            System.out.println("MAC地址列表:");
            for (String mac : info.getMacAddress()) {
                System.out.println("  " + mac);
            }
            
            System.out.println("IP地址列表:");
            for (String ip : info.getIpAddress()) {
                System.out.println("  " + ip);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}